package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.assertj.core.util.Arrays;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author atguigu-mqx
 * @Description TODO
 * @Date 2023/7/5 10:58
 * @Version 1.0
 */
@Service
@RefreshScope
@Slf4j
public class ManageServiceImpl implements ManageService {
    @Value("${minio.endpointUrl}")
    private String endpointUrl;

    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secreKey}")
    private String secreKey;

    //  调用mapper 层 操作哪个表，就用哪个mapper
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private BaseAttrInfoService baseAttrInfoService;

    @Autowired
    private BaseAttrValueService baseAttrValueService;

    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuInfoService spuInfoService;

    @Autowired
    private SpuImageService spuImageService;

    @Autowired
    private SpuPosterService spuPosterService;

    @Autowired
    private SpuSaleAttrService spuSaleAttrService;

    @Autowired
    private SpuSaleAttrValueService spuSaleAttrValueService;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private SkuImageMapper skuImageMapper;

    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuAttrValueService       skuAttrValueService;
    @Autowired
    private SkuImageService           skuImageService;
    @Autowired
    private SkuInfoService            skuInfoService;
    @Autowired
    private SkuSaleAttrValueService   skuSaleAttrValueService;

    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitService rabbitService;


    @Override
    public List<BaseAttrInfo> getAttrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        //  调用mapper 方法。
        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id);
    }

    @Override
    public IPage getSpuInfoList(Page<SpuInfo> spuInfoPage, Long category3Id) {
        //  构建查询条件
        LambdaQueryWrapper<SpuInfo> spuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        spuInfoLambdaQueryWrapper.eq(SpuInfo::getCategory3Id,category3Id).orderByDesc(SpuInfo::getId);
        return spuInfoMapper.selectPage(spuInfoPage,spuInfoLambdaQueryWrapper);
    }

    @Override
    public String fileUpload(MultipartFile file) {
        //  声明一个变量来存储url 路径
        String url = "";
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpointUrl)
                            .credentials(accessKey, secreKey)
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                System.out.println("Bucket "+bucketName+" already exists.");
            }
            //  文件名称不能重复！ 获取到文件的后缀名.tyui456.png .jpg
            String fileName = System.currentTimeMillis()+ UUID.randomUUID().toString().replaceAll("-","")+"."+ FilenameUtils.getExtension(file.getOriginalFilename());
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());
            //  //img14.360buyimg.com/seckillcms/s140x140_jfs/t1/221550/35/31541/78046/64a38ad8F614df9fc/fea441c5e571919d.jpg.webp
            //  http://192.168.200.130:9000/atguigus/
            url = endpointUrl+"/"+bucketName+"/"+fileName;
            System.out.println(url);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        return url;
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        //  调用mapper
        return spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
    }

    @Override
    public IPage<SkuInfo> getSkuInfoList(Page<SkuInfo> skuInfoPage, Long category3Id) {
        //  select * from sku_info where category3_id = 61 order by id desc limit 12,3 ;
        LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        skuInfoLambdaQueryWrapper.eq(SkuInfo::getCategory3Id,category3Id).orderByDesc(SkuInfo::getId);
        return skuInfoMapper.selectPage(skuInfoPage,skuInfoLambdaQueryWrapper);
    }

    @SneakyThrows
    @Override
    public void onSale(Long skuId) {
        //  先删除 sku:[24]:info
        String key = RedisConst.SKUKEY_PREFIX+"["+skuId+"]"+RedisConst.SKUKEY_SUFFIX;
        this.redisTemplate.delete(key);
        //  本质是执行一条更新语句：is_sale = 1
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        this.skuInfoMapper.updateById(skuInfo);

        //  获取到布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
        bloomFilter.add(skuInfo.getId());
        //  睡眠
        Thread.sleep(300);
        //  再删
        this.redisTemplate.delete(key);
        //  需要发送消息，给list 模块.
        //  商品下架：发送的消息内容是由消费者决定的！
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_UPPER,skuId);
    }

    @Override
    @GmallCache(prefix = "sku:",suffix = ":info") // 具有分布式锁的功能.
    public SkuInfo getskuInfo(Long skuId) {
        return getSkuInfoDB(skuId);
        // return getSkuInfoByRedisson(skuId);
        // return getSkuInfoByRedisLua(skuId);
    }

    private SkuInfo getSkuInfoByRedisson(Long skuId) {
        //  声明一个skuInfo
        SkuInfo skuInfo = null;
        //  声明一个缓存的key：sku:skuId:info
        String skuKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKUKEY_SUFFIX;
        try {
            //  获取缓存中的数据
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            if (null == skuInfo){
                //  上锁. 声明一个锁的key
                String locKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                RLock lock = redissonClient.getLock(locKey);
                lock.lock();
                //  上锁 最大等待时间，
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                if (result){
                    //  说明获取到锁.
                      try {
                            //  获取到锁.查询数据库 124
                            skuInfo = this.getSkuInfoDB(skuId);
                            //  判断这个对象是否存在
                            if (null == skuInfo){
                                //  存储一个空值到缓存
                                SkuInfo skuInfo1 = new SkuInfo();
                                this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                                return skuInfo1;
                            }
                            //  存储到缓存
                            this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                            //  返回数据
                          return skuInfo;
                        } finally {
                            //  解锁.
                            lock.unlock();
                        }
                } else {
                    try {
                        //  睡眠 或 睡眠
                        Thread.sleep(300);
                        // 自旋
                        return getskuInfo(skuId);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }else {
                //  从缓存中获取数据并返回.
                return skuInfo;
            }
        } catch (InterruptedException e) {
            log.error("获取数据异常{}", skuId);
            e.printStackTrace();
        }
        //  数据库兜底.
        return getSkuInfoDB(skuId);
    }

    private SkuInfo getSkuInfoByRedisLua(Long skuId) {
        //  声明一个skuInfo
        SkuInfo skuInfo = null;
        //  获取数据库 return getSkuInfoDB(skuId);
        //  声明一个缓存的key：sku:skuId:info
        String skuKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKUKEY_SUFFIX;
        try {
            //  用哪个命令获取? 使用哪种数据类型. SkuInfo -- String
            //  最常用的就是hash, 因为便于对属性的修改！
            skuInfo = (SkuInfo) this.redisTemplate.opsForValue().get(skuKey);
            //  判断
            if (null == skuInfo) {
                //  不存在
                //  设置一个锁 redis+lua
                String locKey = RedisConst.SKUKEY_PREFIX+ skuId +RedisConst.SKULOCK_SUFFIX;
                String token = UUID.randomUUID().toString();
                Boolean result = this.redisTemplate.opsForValue().setIfAbsent(locKey, token, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //  判断是否获取到锁
                if (result){
                    //  获取到锁.查询数据库 124
                    skuInfo = this.getSkuInfoDB(skuId);
                    //  判断这个对象是否存在
                    if (null == skuInfo){
                        //  存储一个空值到缓存
                        SkuInfo skuInfo1 = new SkuInfo();
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        //  删除锁key
                        delLcok(locKey, token);
                        return skuInfo1;
                    }
                    //  存储到缓存
                    this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                    //  删除锁key
                    delLcok(locKey, token);
                    //  返回数据
                    return skuInfo;
                } else {
                   //    没有获取到锁的人，等待自旋.
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    //  自旋.
                    return getskuInfo(skuId);
                }
            } else {
                //  返回缓存数据
                return skuInfo;
            }
        } catch (RuntimeException e) {
            log.error("访问当前商品出现了异常{},"+ skuId);
            e.printStackTrace();
        }
        //  暂时使用数据库查询一下.
        return getSkuInfoDB(skuId);
    }

    /**
     * 删除锁方法
     * @param locKey
     * @param token
     */
    private void delLcok(String locKey, String token) {
        //  定义一个lua脚本：
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
            "then\n" +
            "    return redis.call(\"del\",KEYS[1])\n" +
            "else\n" +
            "    return 0\n" +
            "end";
        //  执行lua脚本：
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText);
        redisScript.setResultType(Long.class);
        //  删除锁
        this.redisTemplate.execute(redisScript, Arrays.asList(locKey), token);
    }

    //  ctrl+alt+m
    private SkuInfo getSkuInfoDB(Long skuId) {
        //  skuInfo + skuImage;  sku_info.id = skuId
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        //  查询skuImage 列表;
        if (null != skuInfo){
            //  select * from sku_image where sku_id = skuId;
            LambdaQueryWrapper<SkuImage> skuImageLambdaQueryWrapper = new LambdaQueryWrapper<>();
            skuImageLambdaQueryWrapper.eq(SkuImage::getSkuId, skuId);
            List<SkuImage> skuImageList = skuImageMapper.selectList(skuImageLambdaQueryWrapper);
            skuInfo.setSkuImageList(skuImageList);
        }
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "categoryView:")
    public BaseCategoryView getCategoryView(Long category3Id) {
        return baseCategoryViewMapper.selectById(category3Id);
    }

    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        //  定义锁的key
        String locKey = "price:"+skuId+":lock";
        //  获取对象并上锁
        RLock lock = redissonClient.getLock(locKey);
        lock.lock();
        try {
            LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            //  id = ?
            skuInfoLambdaQueryWrapper.eq(SkuInfo::getId,skuId);
            //  设置查询的字段
            skuInfoLambdaQueryWrapper.select(SkuInfo::getPrice);
            //  select price from sku_info where id = ?;
            SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoLambdaQueryWrapper);
            if (null == skuInfo){
                return new BigDecimal("0");
            }
            //  获取最新价格
            return skuInfo.getPrice();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //  解锁
            lock.unlock();
        }
        //        boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
        //        //  获取到锁.
        //        if (result){
        //            //  select * from sku_info where id = ?;
        //            //  SkuInfo skuInfo = skuInfoService.getById(skuId);
        //            //  skuInfoService.getOne();
        //            LambdaQueryWrapper<SkuInfo> skuInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //            //  id = ?
        //            skuInfoLambdaQueryWrapper.eq(SkuInfo::getId,skuId);
        //            //  设置查询的字段
        //            skuInfoLambdaQueryWrapper.select(SkuInfo::getPrice);
        //            //  select price from sku_info where id = ?;
        //            SkuInfo skuInfo = skuInfoMapper.selectOne(skuInfoLambdaQueryWrapper);
        //            if (null == skuInfo){
        //                return new BigDecimal("0");
        //            }
        //            //  获取最新价格
        //            return skuInfo.getPrice();
        //        } else {
        //          Thread.sleep(100);
        //          return getSkuPrice(skuId);
        //        }


    }

    @Override
    @GmallCache(prefix = "spuPoster:")
    public List<SpuPoster> getSpuPosterList(Long spuId) {
        //  select * from spu_poster where spu_id = ?;
        //  new LambdaQueryWrapper<SpuPoster>().eq(SpuPoster::getSpuId,spuId) == spu_id = ?
        return spuPosterMapper.selectList(new LambdaQueryWrapper<SpuPoster>().eq(SpuPoster::getSpuId,spuId));
    }

    @Override
    @GmallCache(prefix = "attrList:")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectAttrsInfoList(skuId);
    }

    @Override
    @GmallCache(prefix = "spuSaleAttr:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        //  调用mapper 层
        return spuSaleAttrMapper.selectSpuSaleAttrListCheckBySku(skuId,spuId);
    }

    @Override
    @GmallCache(prefix = "valueIds:")
    public Map getSkuValueIdsMap(Long spuId) {
        //  执行sql 语句：
        //  map 可以代替 实体类.
        /*
            实体类接受数据
            @Data
            class ParamDTO{
                private Long skuId;
                private String valueIds;
             }
            List<ParamDTO> skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
            ParamDTO dto = new ParamDTO();
            dto.setSkuId(21); dto.setValueIds("3724|3727");
            dto.setSkuId(22); dto.setValueIds("3724|3726");

           Map = 本质是key value 键值对
            map.put("sku_id","21");
            map.put("value_ids","3724|3727");

            map.put("sku_id","22");
            map.put("value_ids","3724|3726");
            map.get("sku_id") = dto.get();
            map.put() = dto.set();

            map的 key 相当于实体类的属性 ，put() == set get()==get()
         */
        //  创建一个Map 集合
        HashMap<Object, Object> hashMap = new HashMap<>();
        List<Map> mapList = skuSaleAttrValueMapper.selectSkuValueIdsMap(spuId);
        //  判断循环遍历.
        if (!CollectionUtils.isEmpty(mapList)){
            //  获取集合中的数据.
            mapList.forEach(map -> {
                hashMap.put(map.get("value_ids"),map.get("sku_id"));
            });
        }
        //  返回数据
        return hashMap;
    }

    @Override
    @GmallCache(prefix = "categoryList:")
    public List<JSONObject> getBaseCategoryList() {
        //  创建一个集合
        List<JSONObject> list = new ArrayList<>();
        //  分类包含分类的名称;
        List<BaseCategoryView> baseCategoryViewList = this.baseCategoryViewMapper.selectList(null);
        //  一级分类名称： key Long = category1Id;  List<BaseCategoryView> = value
        Map<Long, List<BaseCategoryView>> listMap = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //  定义一个index 变量
        int index = 1;
        //  获取迭代器
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = listMap.entrySet().iterator();
        while (iterator.hasNext()){
            //  获取一级分类数据
            JSONObject category1 = new JSONObject();

            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            Long category1Id = entry.getKey();
            List<BaseCategoryView> categoryViewList = entry.getValue();
            //  本质是给map 赋值.
            category1.put("index",index);
            category1.put("categoryId",category1Id);
            category1.put("categoryName",categoryViewList.get(0).getCategory1Name());
            //  category1.put("categoryChild","二级分类集合");
            //  变量迭代
            index++;
            //  根据二级分类Id 进行分组
            //  key = category2Id value = List<BaseCategoryView>
            Map<Long, List<BaseCategoryView>> listMap2 = categoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = listMap2.entrySet().iterator();
            //  创建一个二级分类集合对象
            ArrayList<JSONObject> categoryChild2 = new ArrayList<>();
            while (iterator1.hasNext()){
                //  获取二级分类数据
                JSONObject category2 = new JSONObject();
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> categoryViewList1 = entry1.getValue();

                category2.put("categoryId",category2Id);
                category2.put("categoryName",categoryViewList1.get(0).getCategory2Name());
                //  category2.put("categoryChild","三级分类集合");
                //  获取二级分类下的三级分类数据
                List<JSONObject> categoryChild3 = categoryViewList1.stream().map(baseCategoryView -> {
                    //  获取三级级分类数据
                    JSONObject category3 = new JSONObject();
                    category3.put("categoryId", baseCategoryView.getCategory3Id());
                    category3.put("categoryName", baseCategoryView.getCategory3Name());
                    return category3;
                }).collect(Collectors.toList());
                //  将三级分类数据添加到二级分类中
                category2.put("categoryChild",categoryChild3);
                //  将二年级分类对象添加到集合中.
                categoryChild2.add(category2);
            }
            //  将二级分类数据添加到一级中.
            category1.put("categoryChild",categoryChild2);
            //  将一级分类数据添加到list中
            list.add(category1);
        }
        //  返回数据
        return list;
    }

    @Override
    public void cancelSale(Long skuId) {
        //  先删除 sku:[24]:info
        String key = RedisConst.SKUKEY_PREFIX+"["+skuId+"]"+RedisConst.SKUKEY_SUFFIX;
        this.redisTemplate.delete(key);

        //  本质是执行一条更新语句：is_sale = 0
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        this.skuInfoMapper.updateById(skuInfo);
        //  睡眠
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        this.redisTemplate.delete(key);
        //  商品下架：发送的消息内容是由消费者决定的！
        this.rabbitService.sendMsg(MqConst.EXCHANGE_DIRECT_GOODS,MqConst.ROUTING_GOODS_LOWER,skuId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
        sku_attr_value
        sku_image
        sku_info
        sku_sale_attr_value
         */
        //  result==受影响的行数
        //  skuInfoMapper.insert(skuInfo);
        skuInfoService.save(skuInfo);
        //  sku_image
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)){
            skuImageList.forEach(skuImage -> {
                skuImage.setSkuId(skuInfo.getId());
            });
            //  批量保存
            this.skuImageService.saveBatch(skuImageList);
        }
        //  sku_attr_value
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)){
            skuAttrValueList.forEach(skuAttrValue -> {
                skuAttrValue.setSkuId(skuInfo.getId());
            });
            //  批量保存
            this.skuAttrValueService.saveBatch(skuAttrValueList);
        }
        //  sku_sale_attr_value
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)){
            skuSaleAttrValueList.forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
            });
            //  批量保存
            this.skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);
        }

        //  获取到布隆过滤器
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);
        bloomFilter.add(skuInfo.getId());

    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        //  select * from spu_image where spu_id = ? and is_delete = 0;
        return spuImageMapper.selectList(new LambdaQueryWrapper<SpuImage>().eq(SpuImage::getSpuId,spuId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
        //  保存spuInfo , 需要将数据放入对应的表中.
        //        spu_image
        //        spu_info
        //        spu_poster
        //        spu_sale_attr
        //        spu_sale_attr_value
        spuInfoService.save(spuInfo);
        //  获取到spuImage 集合
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)){
            spuImageList.forEach(spuImage -> {
                spuImage.setSpuId(spuInfo.getId());
            });
            //  批量插入数据
            spuImageService.saveBatch(spuImageList);
        }
        //  获取spuPoster 集合
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)){
            spuPosterList.forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
            });
            //  批量插入数据
            spuPosterService.saveBatch(spuPosterList);
        }
        //  获取销售属性
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)){
            spuSaleAttrList.forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                //  获取到销售属性值集合
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)){
                    spuSaleAttrValueList.forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                    });
                    //  批量保存数据
                    spuSaleAttrValueService.saveBatch(spuSaleAttrValueList);
                }
            });
            //  批量插入数据
            spuSaleAttrService.saveBatch(spuSaleAttrList);
        }
    }

    @Override
    public Result getBaseSaleAttrList() {
        List<BaseSaleAttr> baseSaleAttrList = baseSaleAttrMapper.selectList(null);
        //  判断集合是否为空
        if (null == baseSaleAttrList) {
            return Result.fail();
        }
        //  返回真实数据
        return Result.ok(baseSaleAttrList);
    }

    @Override
    public BaseAttrInfo getBaseAttrInfo(Long attrId) {
        //  根据主键查询baseAttrInfo;
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        //  判断
        if (null != baseAttrInfo){
            baseAttrInfo.setAttrValueList(this.getAttrValueList(attrId));
        }
        //  返回数据
        return baseAttrInfo;
    }

    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        //  就是单sql
        LambdaQueryWrapper<BaseAttrValue> baseAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseAttrValueLambdaQueryWrapper.eq(BaseAttrValue::getAttrId,attrId);
        //  返回数据
        return baseAttrValueMapper.selectList(baseAttrValueLambdaQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        //  判断 base_attr_info 表
        if (baseAttrInfo.getId()==null){
            //  保存平台属性
            //  baseAttrInfoMapper.insert(baseAttrInfo);
            baseAttrInfoService.save(baseAttrInfo);
        } else {
            //  修改平台属性
            this.baseAttrInfoMapper.updateById(baseAttrInfo);
            //  删除平台属性值的集合数据.
            LambdaQueryWrapper<BaseAttrValue> baseAttrValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseAttrValueLambdaQueryWrapper.eq(BaseAttrValue::getAttrId,baseAttrInfo.getId());
            this.baseAttrValueMapper.delete(baseAttrValueLambdaQueryWrapper);
        }

        //  base_attr_value;
        //  获取到平台属性值集合
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //  将数据添加到平台属性值中！
        if (!CollectionUtils.isEmpty(attrValueList)){
            //  泛型T是指：BaseAttrValue
            attrValueList.forEach((baseAttrValue)->{
                //  添加的时候，页面没有传递attrId
                //  @TableId(type = IdType.AUTO) 当执行完成添加之后获取主键自增！
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                //  baseAttrValueMapper.insert(baseAttrValue);
            });
            //  调用服务层的批量保存方法！
            this.baseAttrValueService.saveBatch(attrValueList);
        }

    }

    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        //  构造条件
        LambdaQueryWrapper<BaseCategory3> baseCategory3LambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseCategory3LambdaQueryWrapper.eq(BaseCategory3::getCategory2Id,category2Id);
        //  用这个条件查询！
        return baseCategory3Mapper.selectList(baseCategory3LambdaQueryWrapper);
    }

    @Override
    public List<BaseCategory2> getCategory2(Long category1Id) {
        //  select * from base_category2 where base_category2.category1_id = ? and is_deleted = 0;
        //        QueryWrapper<BaseCategory2> baseCategory2QueryWrapper = new QueryWrapper<>();
        //        baseCategory2QueryWrapper.eq("category1_id",category1Id);
        //        return baseCategory2Mapper.selectList(baseCategory2QueryWrapper);
        LambdaQueryWrapper<BaseCategory2> baseCategory2LambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseCategory2LambdaQueryWrapper.eq(BaseCategory2::getCategory1Id,category1Id);
        return baseCategory2Mapper.selectList(baseCategory2LambdaQueryWrapper);
    }

    @Override
    public List<BaseCategory1> getCategory1() {
        //  select * from base_category1 where is_deleted = 0;
        return baseCategory1Mapper.selectList(null);
    }
}
